package com.cloudservice.ccs.biz.impl;

import com.cloudservice.ccs.biz.INoticeBiz;
import com.cloudservice.ccs.entity.Notice;
import com.cloudservice.ccs.exception.NoticeException;
import com.cloudservice.ccs.mapper.NoticeMapper;
import com.cloudservice.ccs.model.ApiResult;
import com.cloudservice.ccs.model.NoticeConnectQuery;
import com.cloudservice.ccs.websocket.NoticeAndSystemMessageServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class NoticeImpl implements INoticeBiz {

    private final Logger logger = LoggerFactory.getLogger(NoticeImpl.class);

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void save(Notice notice) {
        int result = noticeMapper.save(notice);
        if (result == 0) {
            throw new NoticeException("Create Notice entity error");
        }
        try {
            NoticeAndSystemMessageServer.getSessionPool().broadcast(ApiResult.successWithData(notice));
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error when broadcasting new notice: " + e.getClass().getName() + ": " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Integer id, Notice notice) {
        int result = noticeMapper.update(id, notice);
        if (result == 0) {
            throw new NoticeException("Update Notice entity error");
        }
    }

    @Override
    public void partialUpdate(Integer id, Map<String, Object> fields) {
        int result = noticeMapper.partialUpdate(id, fields);
        if (result == 0) {
            throw new NoticeException("Partial update Notice failed");
        }
    }

    @Override
    public void delete(Integer id) {
        int result = noticeMapper.delete(id);
        if (result == 0) {
            throw new NoticeException("Delete Notice entity error");
        }
    }

    @Override
    public Notice getOne(Integer id) {
        Notice notice = noticeMapper.getOne(id);
        if (notice == null) {
            throw new NoticeException("Get Notice entity error: no such entity");
        }
        return notice;
    }

    @Override
    public List<NoticeConnectQuery> getAll() {
        return noticeMapper.getAll();
    }

    @Override
    public NoticeConnectQuery queryCustomerService(Integer id) {
        NoticeConnectQuery noticeConnectQuery = noticeMapper.queryCustomerService(id);
        if (noticeConnectQuery == null) {
            throw new NoticeException("Get Notice entity error: no such entity");
        }
        return noticeConnectQuery;
    }
}
